﻿using System;
using System.Collections.Generic;
using System.Text;
using Task.Entity;
using System.Collections;
using Task.Logic.Interface;
using App.Configuration;
using System.Web;
using App.Web.Process; 
using App.Service;
using App.Data;
using App.Integration;


namespace Task.Logic
{
    internal class TaskLogic:ITask,IProcess
    { 
        public virtual List<TaskEntity> GetMyTask(string filter, int skipResults, int maxResults)
        {
            Hashtable table=new Hashtable();
            table.Add("filter",filter);
            return DataAccess.Instance("BusinessDB").GetList<TaskEntity>("TaskLogic_GetMyTask", table, skipResults, maxResults);
        }

        public virtual int GetMyTaskCount(string filter)
        {
            Hashtable table = new Hashtable();
            table.Add("filter", filter);
            return DataAccess.Instance("BusinessDB").GetEntity<int>("TaskLogic_GetMyTaskCount", table);
        }

        public virtual List<TaskEntity> GetMyApproval(string filter, int skipResults, int maxResults)
        {
            Hashtable table = new Hashtable();
            table.Add("filter", filter);
            return DataAccess.Instance("BusinessDB").GetList<TaskEntity>("TaskLogic_GetMyApproval", table, skipResults, maxResults);
        }

        public virtual int GetMyApprovalCount(string filter)
        {
            Hashtable table = new Hashtable();
            table.Add("filter", filter);
            return DataAccess.Instance("BusinessDB").GetEntity<int>("TaskLogic_GetMyApprovalCount", table);
        }

        public virtual List<TaskEntity> GetMyRequest(string filter, int skipResults, int maxResults)
        {
            Hashtable table = new Hashtable();
            table.Add("filter", filter);
            return DataAccess.Instance("BusinessDB").GetList<TaskEntity>("TaskLogic_GetMyRequest", table, skipResults, maxResults);
        }

        public virtual int GetMyRequestCount(string filter)
        {
            Hashtable table = new Hashtable();
            table.Add("filter", filter);
            return DataAccess.Instance("BusinessDB").GetEntity<int>("TaskLogic_GetMyRequestCount", table);
        }


        public virtual TaskEntity GetEntity(string taskID)
        {
            return DataAccess.Instance("BusinessDB").GetEntity<TaskEntity>("TaskLogic_GetEntity", taskID);
        }

        public virtual TaskEntity GetStartEntity(string taskID)
        {
            return DataAccess.Instance().GetEntity<TaskEntity>("TaskLogic_GetStartEntity", taskID);
        }

        public virtual void InsertBackFromLog(string processName, int incident)
        {
            Hashtable table = new Hashtable();
            table.Add("processName", processName);
            table.Add("incident", incident);
            DataAccess.Instance("BusinessDB").Insert("TaskLogic_InsertBackFromLog", table);
        }


        public virtual string GetTaskUrl(string taskID, string userName)
        {
            TaskEntity entity = new TaskEntity();
            if (taskID.StartsWith("S"))
            {
                entity = GetStartEntity(taskID);
            }
            else
            {
                entity = GetEntity(taskID);
            }
            string processName = "";
            string stepLabel = "";
            int incident;
            if (entity == null)
            {
                Ultimus.WFServer.Task task = new Ultimus.WFServer.Task();
                task.InitializeFromTaskId(taskID);
                processName = task.strProcessName.Trim();
                stepLabel = task.strStepName.Trim();
                incident = task.nIncidentNo;
            }
            else
            {
                processName = entity.ProcessName.Trim();
                stepLabel = entity.StepLabel.Trim();
                incident = entity.Incident;
            }

            string page = ConfigurationManager.GetStepPage(processName,stepLabel);
            string url = "";
            if (string.IsNullOrEmpty(page)) //Standard Form
            {
                string result = "";
                Ultimus.WFServer.Task t = new Ultimus.WFServer.Task();
                t.InitializeFromTaskId(taskID);
                t.ExtractFormURL(out result);
                if (!string.IsNullOrEmpty(result))
                {
                    string ServerName = HttpContext.Current.Request.Url.Host;
                    url = "http://" + ServerName + "/Ultweb/" + result;
                    HttpContext.Current.Response.AddHeader("Ultimus Workflow1", "Ultimus Workflow");
                    HttpContext.Current.Response.Cookies["TaskID"].Value = taskID;
                    HttpContext.Current.Response.Cookies["TaskID"].Path = @"/";
                    HttpContext.Current.Response.Cookies["UserID"].Value = userName;
                    HttpContext.Current.Response.Cookies["UserID"].Path = @"/";
                }
                else
                {
                    if (entity != null) //有这个task,把该task再插入回来
                    {
                        InsertBackFromLog(entity.ProcessName, entity.Incident);
                        t.InitializeFromTaskId(taskID);
                        t.ExtractFormURL(out result);
                        if (!string.IsNullOrEmpty(result))
                        {
                            string ServerName = HttpContext.Current.Request.Url.Host;
                            url = "http://" + ServerName + "/Ultweb/" + result;
                            HttpContext.Current.Response.AddHeader("Ultimus Workflow1", "Ultimus Workflow");
                            HttpContext.Current.Response.Cookies["TaskID"].Value = taskID;
                            HttpContext.Current.Response.Cookies["TaskID"].Path = @"/";
                            HttpContext.Current.Response.Cookies["UserID"].Value = userName;
                            HttpContext.Current.Response.Cookies["UserID"].Path = @"/";
                        }
                    }
                    else
                    {
                        throw new Exception(Task.Content.lang.OpenForm_CannotLoadTask);
                    }
                }
            }
            else //.net Form
            {
                url = "http://" + HttpContext.Current.Request.Url.Host+":"
                    +HttpContext.Current.Request.Url.Port+"/"+ page + "?ProcessName=" + processName + "&StepName=" + stepLabel + "&Incident="
                   + incident + "&TaskID=" + taskID + "&UserName=" + HttpContext.Current.Server.UrlEncode(SSOUtil.Context.GetLoginedUser().UserAccount);
            }
            return url;
        }

        public virtual Hashtable LoadTask(string taskId)
        {
            Ultimus.WFServer.Task task = new Ultimus.WFServer.Task();
            bool flag = task.InitializeFromTaskId(taskId);
            Hashtable table = new Hashtable();
            if (flag)
            {
                Ultimus.WFServer.Variable[] vs ;
                string strError = "";
                task.GetAllTaskVariables(out vs, out strError);
                if (vs == null)
                {
                    return table;
                }
                foreach (Ultimus.WFServer.Variable var in vs)
                {
                    if (var.objVariableValue != null && var.objVariableValue.Length > 0)
                    {
                        table.Add(var.strVariableName, var.objVariableValue[0]);
                    }
                }
            }
            return table;
        }

        public virtual Ultimus.WFServer.Variable[] GetVariables(Hashtable vars)
        {
            Ultimus.WFServer.Variable[] vs = new Ultimus.WFServer.Variable[vars.Count];
            int i = 0;
            foreach (string str in vars.Keys)
            {
                Ultimus.WFServer.Variable pvar = new Ultimus.WFServer.Variable();
                pvar.strVariableName = str;
                object value = vars[str];
                pvar.objVariableValue = new object[] { value };
                vs[i] = pvar;
                i++;
            }
            return vs;
        }

        public virtual string GetCurrentUser()
        {
            return SSOUtil.Context.GetLoginedUser().UserAccount;
        }

        /// <summary>
        /// 提交任务
        /// </summary>
        /// <param name="userName">任务所属的用户名</param>
        /// <param name="taskId">任务ID</param>
        /// <param name="vars">电子表格变量</param>
        /// <param name="sync">true:同步 false:异步</param>
        /// <returns>同步>0的流程实例号 同步=0 失败 异步：-1</returns>
        public virtual string SubmitTask(string userName, string taskId, Hashtable vars, bool sync)
        {
            Ultimus.WFServer.Task task = new Ultimus.WFServer.Task();
            bool flag = task.InitializeFromTaskId(taskId);
            int incident = 0;
            if (flag)
            {
                Ultimus.WFServer.Variable[] vs = GetVariables(vars);
                string strError = "";
                if (!sync)
                {
                    incident = -1;
                }
                task.SendFrom(userName, vs, "", "summary1", ref incident, out strError);
            }
            return incident.ToString();
        }

        public virtual string ReturnTask(string userName, string taskId, Hashtable vars, bool sync)
        {
            Ultimus.WFServer.Task task = new Ultimus.WFServer.Task();
            bool flag = task.InitializeFromTaskId(taskId);
            string strError = "";
            if (flag)
            {
                Ultimus.WFServer.Variable[] vs = GetVariables(vars);
                task.Return(vs, "", "",  out strError);

            }
            return strError;
        }

        public virtual string ReturnApplicantTask(string userName, string taskId, Hashtable vars, bool sync)
        {
            Ultimus.WFServer.Task task = new Ultimus.WFServer.Task();
            bool flag = task.InitializeFromTaskId(taskId);
            string strError = "";
            if (flag)
            {
                Ultimus.WFServer.Variable[] vs = GetVariables(vars);
                task.Return(vs, "", "", out strError);

            }
            return strError;
        }

        public virtual string RejectTask(string userName, string taskId, Hashtable vars, bool sync)
        {
            return AbortProcess(userName,taskId,vars,sync);
        }

        public virtual string AbortProcess(string userName, string taskId, Hashtable vars, bool sync)
        {
            Ultimus.WFServer.Task task = new Ultimus.WFServer.Task();
            bool flag = task.InitializeFromTaskId(taskId);
            string strError = "";
            if (flag)
            {
                Ultimus.WFServer.Incident incident=new Ultimus.WFServer.Incident();
                incident.LoadIncident(task.strProcessName, task.nIncidentNo);
                incident.AbortIncident(userName, "", out strError);
            }
            return strError;
        }


        public virtual List<ProcessEntity> GetProcessList(string userName)
        {

            List<ProcessEntity> initProcessList = new List<ProcessEntity>();
            //load init process
            Ultimus.WFServer.TasklistFilter filter = new Ultimus.WFServer.TasklistFilter();
            filter.strArrUserName = new string[1] { SSOUtil.Context.GetLoginedUser().UserAccount };
            Ultimus.WFServer.Tasklist taskList = new Ultimus.WFServer.Tasklist();

            filter.nFiltersMask = Ultimus.WFServer.Filters.nFilter_Initiate;
            taskList.LoadFilteredTasks(filter);
            for (int i = 0; i < taskList.GetTasksCount(); i++)
            {
                ProcessEntity process = new ProcessEntity();
                process.ProcessName = taskList.GetAt(i).strProcessName;
                initProcessList.Add(process);
            }
            return initProcessList;
        }
    }
}
